package cn.edu.ctbu.dp01.service;

import cn.edu.ctbu.dp01.constant.REnum;
import cn.edu.ctbu.dp01.dao.TeacherRepository;
import cn.edu.ctbu.dp01.entity.Teacher;
import cn.edu.ctbu.dp01.exception.RException;
import org. springframework. beans. factory. annotation. Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org. springframework. stereotype. Service;
import java. util. List;

@Service
public class TeacherService {

    @Autowired
    public TeacherRepository teacherRepository;

    /**
     * 读所有的教师列表
     *
     * @ return List Teacher
     */
    public List<Teacher> getAll() {

        return teacherRepository.findAll();
    }

    public Page<Teacher> getAll(Pageable pageable){
        return teacherRepository.findAll(pageable);
    }
    public Page<Teacher> getAll(Example<Teacher> example, Pageable pageable) {

        return teacherRepository.findAll(example, pageable);
    }

    public Teacher findById(int id) {
        return teacherRepository.findById(id).get();
    }

    public Teacher add(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    public Teacher update(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    public void delete(Integer id) {
        teacherRepository.deleteById(id);
    }

    public Teacher validateUsernameAndPasssword(String tno, String password) throws Exception {

        List<Teacher> teachers = teacherRepository.findByTno(tno);
        if (teachers.size() > 0) {
//可能对password加密，但我们暂时不做处理
            Teacher teacher = teachers.get(0);
            if (teacher.getPassword().equals(password)) {
//成功
                return teacher;
            } else {
                throw new RException(REnum.LOGIN_ERR);
            }
        } else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }
}



